using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.Tilemaps;
using System.Text.RegularExpressions;

public class MapLoaderWithInput : MonoBehaviour
{
    [Header("UI 控件 (TMP)")]
    [SerializeField] private GameObject inputPanel;           // 输入面板
    [SerializeField] private TMP_InputField mapInputField;    // TMP 输入框
    [SerializeField] private Button loadButton;               // 加载按钮
    [SerializeField] private Button resetButton;              // 重置按钮

    [Header("地图配置")]
    [SerializeField] private TileBase wallTile;               // 墙的瓦片
    [SerializeField] private TileBase goalTile;               // 终点瓦片（绿色）
    [SerializeField] private Tilemap targetTilemap;           // 已有的 Tilemap

    private GameObject playerInstance;                        // 当前玩家实例
    private bool isMapLoaded = false;

    private void Start()
    {
        // 初始化按钮事件
        if (loadButton != null)
        {
            loadButton.onClick.AddListener(OnLoadButtonClick);
        }

        if (resetButton != null)
        {
            resetButton.onClick.AddListener(OnResetButtonClick);
        }

        // 默认显示输入框面板
        if (inputPanel != null)
        {
            inputPanel.SetActive(true);
        }

        isMapLoaded = false;
        
        // 查找现有的玩家对象
        FindPlayerObject();
    }

    private void FindPlayerObject()
    {
        // 查找场景中带有 Player 标签的对象
        playerInstance = GameObject.FindGameObjectWithTag("Player");
        if (playerInstance == null)
        {
            Debug.LogWarning("场景中未找到带有 'Player' 标签的对象！");
        }
    }

    private void OnLoadButtonClick()
    {
        string mapData = mapInputField.text.Trim();
        if (string.IsNullOrEmpty(mapData))
        {
            Debug.LogWarning("请输入地图数据！");
            return;
        }

        // 隐藏输入面板
        if (inputPanel != null)
        {
            inputPanel.SetActive(false);
        }

        // 解析并加载地图
        LoadMapFromString(mapData);

        isMapLoaded = true;
    }

    private void OnResetButtonClick()
    {
        // 显示输入面板
        if (inputPanel != null)
        {
            inputPanel.SetActive(true);
        }

        // 清空输入框
        if (mapInputField != null)
        {
            mapInputField.text = "";
        }

        // 清除地图
        if (targetTilemap != null)
        {
            targetTilemap.ClearAllTiles();
        }

        // 重新查找玩家对象
        FindPlayerObject();

        isMapLoaded = false;
    }

    private void LoadMapFromString(string mapString)
    {
        // 按行分割
        string[] lines = mapString.Split(new[] { "\r\n", "\r", "\n" }, System.StringSplitOptions.RemoveEmptyEntries);
        if (lines.Length == 0)
        {
            Debug.LogWarning("地图数据为空！");
            return;
        }

        // 清空现有地图
        if (targetTilemap != null)
        {
            targetTilemap.ClearAllTiles();
        }

        Vector3? spawnPosition = null;
        Vector3? goalPosition = null;

        // 解析每一行
        for (int y = 0; y < lines.Length; y++)
        {
            string line = lines[y].Trim();
            if (string.IsNullOrEmpty(line)) continue;

            // 使用正则表达式分割多个空格或制表符
            string[] cells = Regex.Split(line, @"\s+");

            for (int x = 0; x < cells.Length; x++)
            {
                if (int.TryParse(cells[x], out int cellValue))
                {
                    Vector3Int cellPos = new Vector3Int(x, -y, 0);

                    switch (cellValue)
                    {
                        case 0: // 空地
                            break;

                        case 1: // 墙
                            if (targetTilemap != null)
                            {
                                targetTilemap.SetTile(cellPos, wallTile);
                            }
                            break;

                        case 2: // 玩家出生点
                            spawnPosition = targetTilemap?.GetCellCenterWorld(cellPos);
                            break;

                        case 3: // 终点
                            goalPosition = targetTilemap?.GetCellCenterWorld(cellPos);
                            if (targetTilemap != null)
                            {
                                targetTilemap.SetTile(cellPos, goalTile);
                            }
                            break;

                        default:
                            Debug.LogWarning($"未知地图值: {cellValue} at ({x}, {y})");
                            break;
                    }
                }
                else
                {
                    Debug.LogWarning($"无法解析单元格 ({x}, {y}): '{cells[x]}'");
                }
            }
        }

        // 移动现有的玩家对象
        if (spawnPosition.HasValue && playerInstance != null)
        {
            // 使用 Rigidbody2D 或直接设置位置
            if (playerInstance.TryGetComponent<Rigidbody2D>(out Rigidbody2D rb))
            {
                rb.position = spawnPosition.Value;
                rb.velocity = Vector2.zero;
                rb.angularVelocity = 0;
            }
            else
            {
                playerInstance.transform.position = spawnPosition.Value;
            }
            
            Debug.Log($"Player 已移动到出生点: {spawnPosition.Value}");
        }
        else if (playerInstance == null)
        {
            Debug.LogError("未找到带有 'Player' 标签的对象！");
        }
        else
        {
            Debug.LogWarning("地图中未找到玩家出生点 (2)");
        }

        // 终点提示
        if (goalPosition.HasValue)
        {
            Debug.Log($"终点已标记在: {goalPosition.Value}");
        }

        Debug.Log("地图加载完成！");
    }

    // 可选：定期刷新玩家对象（如果场景中对象被销毁重建）
    private void Update()
    {
        if (!isMapLoaded && playerInstance == null)
        {
            FindPlayerObject();
        }
    }
}